第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
输出三行,分别表示二叉树的先序,中序和后序。
3 1 1 2 3 2 0 0 3 0 0
1 2 3 2 1 3 2 3 1
def inorder(root): if tree_dict[root][0]: inorder(tree_dict[root][0]) print(root, end=' ') if tree_dict[root][1]: inorder(tree_dict[root][1]) def preorder(root): print(root, end=' ') if tree_dict[root][0]: preorder(tree_dict[root][0]) if tree_dict[root][1]: preorder(tree_dict[root][1]) def postorder(root): if tree_dict[root][0]: postorder(tree_dict[root][0]) if tree_dict[root][1]: postorder(tree_dict[root][1]) print(root, end=' ') tree_dict = dict() n, root = tuple(map(int, input().strip().split())) for i in range(n): fa, lch, rch = list(map(int, input().strip().split())) tree_dict[fa] = (lch, rch) preorder(root) print() inorder(root) print() postorder(root)